
/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.xutils.demo.slice;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import org.xutils.DbManager;
import org.xutils.common.util.LogUtil;
import org.xutils.demo.ResourceTable;
import org.xutils.demo.db.ChildInfo;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库操作示例
 */
public class DbAbilitySlice extends AbilitySlice {

    @ViewInject(ResourceTable.Id_btn_add)
    Button btnDbAdd;

    @ViewInject(ResourceTable.Id_btn_del)
    Button btnDbDel;

    @ViewInject(ResourceTable.Id_btn_update)
    Button btnDbUpdate;

    @ViewInject(ResourceTable.Id_btn_select)
    Button btnDbSelect;

    @ViewInject(ResourceTable.Id_text_show)
    Text txtShow;

    DbManager.DaoConfig daoConfig;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_db);
        x.view().inject(this);

        daoConfig = new DbManager.DaoConfig()
                .setDbName("testaa.db")
                // 不设置dbDir时, 默认存储在app的私有目录.
                .setDbDir(new File("/sdcard")) // "sdcard"的写法并非最佳实践, 这里为了简单, 先这样写了.
                .setDbVersion(2)
                .setDbOpenListener(new DbManager.DbOpenListener() {
                    @Override
                    public void onDbOpened(DbManager db) {
                        // 开启WAL, 对写入加速提升巨大
//                        db.getDatabase().enableWriteAheadLogging();
                    }
                })
                .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                    @Override
                    public void onUpgrade(DbManager db, int oldVersion, int newVersion) {
                        // TODO: ...
                        // db.addColumn(...);
                        // db.dropTable(...);
                        // ...
                        // or
                        // db.dropDb();
                    }
                });


    }

    @Event(value = {ResourceTable.Id_btn_add, ResourceTable.Id_btn_del, ResourceTable.Id_btn_update, ResourceTable.Id_btn_select})
    private void onTest1Click(Component view) {
        if (view.getId() == ResourceTable.Id_btn_add) {
            dbSave();
        }
        if (view.getId() == ResourceTable.Id_btn_del) {
            dbDel();
        }
        if (view.getId() == ResourceTable.Id_btn_update) {
            dbUpdate();
        }
        if (view.getId() == ResourceTable.Id_btn_select) {
            dbSelect();
        }
    }

    /**
     * 添加
     */
    private void dbSave() {
        try {
            btnDbAdd.setText("添加");
            DbManager db = x.getDb(daoConfig);
            ArrayList<ChildInfo> childInfos = new ArrayList<>();
            childInfos.add(new ChildInfo("zhangsan"));
            childInfos.add(new ChildInfo("lisi"));
            childInfos.add(new ChildInfo("wangwu"));
            childInfos.add(new ChildInfo("zhaoliu"));
            childInfos.add(new ChildInfo("qianqi"));
            childInfos.add(new ChildInfo("sunba"));
            db.save(childInfos);
            btnDbAdd.setText("添加成功");
        } catch (Exception e) {
            LogUtil.e(this.getClass().getName()+"---error:"+e);
        }
    }

    /**
     * 删除
     */
    private void dbDel() {
        try {
            btnDbDel.setText("删除");
            DbManager db = x.getDb(daoConfig);
            db.delete(ChildInfo.class);
            btnDbDel.setText("删除成功");
        } catch (Exception e) {
            LogUtil.e(this.getClass().getName()+"---error:"+e);
        }
    }

    /**
     * 修改
     */
    private void dbUpdate() {
        try {
            btnDbUpdate.setText("修改");
            DbManager db = x.getDb(daoConfig);
            ChildInfo first = db.findFirst(ChildInfo.class);
            first.setcName("zhansan2");
            db.update(first, "c_name"); //c_name：表中的字段名
            btnDbUpdate.setText("修改成功");
        } catch (Exception e) {
            LogUtil.e(this.getClass().getName()+"---error:"+e);
        }
    }

    /**
     * 查询
     */
    private void dbSelect() {
        try {
            btnDbSelect.setText("查询");
            DbManager db = x.getDb(daoConfig);
            String result = "";
//            ChildInfo first = db.findFirst(ChildInfo.class);
//            List<ChildInfo> all = db.selector(ChildInfo.class).where("id", ">", 0).and("id", "<", 4).findAll();
            List<ChildInfo> all = db.selector(ChildInfo.class).findAll();
            for (ChildInfo childInfo : all) {
                result += childInfo.toString()+"\n";
            }
            btnDbSelect.setText("查询成功");
            txtShow.setText("查询结果:"+result);
        } catch (Exception e) {
            LogUtil.e(this.getClass().getName()+"---error:"+e);
        }
    }


    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
}
